//
// ***********************************************
// *    ___________   ___________  __      __    *
// *   |______  __/  /_____  ___/  \ \    / /    *
// *         / /          / /       \ \  / /     *
// *        / /          / /         \ \/ /      *
// *       / /          / /           \  /       *
// *      / /______    / /            / /        *
// *     /________/   /_/            /_/         *
// *                                             *
// ***********************************************
//
//   AdViewController.m
//   InterviewDemo
//   
//   Created  by wanmeizty on 26/12/2019
//   Modified by Tiyon  qq 897574226  
//   Copyright © 2019 wanmeizty. All rights reserved.
//   
   

#import "AdViewController.h"
#import <BUAdSDK/BUAdSDK.h>
#import <BUAdSDK/BURewardedVideoAd.h>
#import <PTFakeTouch/PTFakeTouch.h>
#import "TimerManager.h"
#import "SubAdViewController.h"

static int adTime = 0;

@interface AdViewController ()<BUNativeAdDelegate,BUNativeAdsManagerDelegate,BUNativeExpressAdViewDelegate,BUNativeExpressBannerViewDelegate,BURewardedVideoAdDelegate,BUNativeExpressRewardedVideoAdDelegate,BUNativeExpressFullscreenVideoAdDelegate,UITableViewDelegate,UITableViewDataSource>
@property (strong,nonatomic) BUNativeExpressRewardedVideoAd * rewardedAd;
@property (strong,nonatomic) BUNativeExpressFullscreenVideoAd * fullVideoAd;
@property (strong,nonatomic) NSMutableArray * expressAdViews;
@property (strong,nonatomic) UITableView * tableview;

@property (strong,nonatomic) BUNativeExpressAdManager * nativeExpressAdManager;
@end

@implementation AdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.expressAdViews = [NSMutableArray array];
    
    
//     [self loadBannerAd];
//    [self loadRewardVideo];
    
    
   
    self.tableview = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    [self.view addSubview:self.tableview];
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"BUDNativeExpressCell"];
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"BUDSplitNativeExpressCell"];
    
    UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];
    [btn setTitle:@"激励视频" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    self.tableview.tableHeaderView = btn;
    [self loadFullVideo];
    
//    [self loadNativeAd];
//    [self loadDrawaData];
    [self loadFeadAd];
    
//    for (int i = 0; i < 10000; i ++ ) {
//        sleep(5);
//       [self loadFeadAd];
//    }
    
    // Do any additional setup after loading the view.
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    __weak __typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf goSubAdVC];
    });
}

-(void)testClick{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 100, 200, 200)];
    button.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:button];
    [button setTitle:@"test" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [button sendActionsForControlEvents:UIControlEventTouchUpInside]; //代码自动点击
}

- (void)clickBtn:(UIButton *)btn{
    
    NSLog(@"我被点击啦");
    
}

-(void)loadFullVideo{
    BUNativeExpressFullscreenVideoAd *fullscreenAd = [[BUNativeExpressFullscreenVideoAd alloc] initWithSlotID:@"940033111"];
    fullscreenAd.delegate = self;
    [fullscreenAd loadAdData];
    self.fullVideoAd = fullscreenAd;
}

- (void)nativeExpressFullscreenVideoAdDidLoad:(BUNativeExpressFullscreenVideoAd *)fullscreenVideoAd{
    
}
- (void)nativeExpressFullscreenVideoAd:(BUNativeExpressFullscreenVideoAd *)fullscreenVideoAd didFailWithError:(NSError *_Nullable)error{
    
}

- (void)nativeExpressFullscreenVideoAdViewRenderSuccess:(BUNativeExpressFullscreenVideoAd *)rewardedVideoAd{
    
   
}


- (void)nativeExpressFullscreenVideoAdViewRenderFail:(BUNativeExpressFullscreenVideoAd *)rewardedVideoAd error:(NSError *_Nullable)error{
    
}

- (void)nativeExpressFullscreenVideoAdDidDownLoadVideo:(BUNativeExpressFullscreenVideoAd *)fullscreenVideoAd{
    
}
- (void)nativeExpressFullscreenVideoAdWillVisible:(BUNativeExpressFullscreenVideoAd *)fullscreenVideoAd{
    
}
- (void)nativeExpressFullscreenVideoAdDidVisible:(BUNativeExpressFullscreenVideoAd *)fullscreenVideoAd{
    
}
- (void)nativeExpressFullscreenVideoAdDidClick:(BUNativeExpressFullscreenVideoAd *)fullscreenVideoAd{
    
}
- (void)nativeExpressFullscreenVideoAdDidClickSkip:(BUNativeExpressFullscreenVideoAd *)fullscreenVideoAd{
    
}
- (void)nativeExpressFullscreenVideoAdWillClose:(BUNativeExpressFullscreenVideoAd *)fullscreenVideoAd{
    
}
- (void)nativeExpressFullscreenVideoAdDidClose:(BUNativeExpressFullscreenVideoAd *)fullscreenVideoAd{
    
    [self.fullVideoAd loadAdData];
}

-(void)click:(UIButton *)btn{
//    [self.rewardedAd showAdFromRootViewController:self];
    
//    [self.fullVideoAd showAdFromRootViewController:self];
    
    
}

-(void)goSubAdVC{
    SubAdViewController * advc = [[SubAdViewController alloc] init];
    [self.navigationController pushViewController:advc animated:YES];
}

#pragma mark -- 激励视频
-(void)loadRewardVideo{

//    BURewardedVideoModel *model = [[BURewardedVideoModel alloc] init];
//    model.userId = @"123456";
//    BURewardedVideoAd * videoView = [[BURewardedVideoAd alloc] initWithSlotID:@"940033495" rewardedVideoModel:model];
//    videoView.delegate = self;
//    [videoView loadAdData];
    
    BURewardedVideoModel *model = [[BURewardedVideoModel alloc] init];
    model.userId = @"123";
    BUNativeExpressRewardedVideoAd *rewardedAd = [[BUNativeExpressRewardedVideoAd alloc] initWithSlotID:@"940033495" rewardedVideoModel:model];
    rewardedAd.delegate = self;
    self.rewardedAd = rewardedAd;
    [rewardedAd loadAdData];

}

- (void)nativeExpressRewardedVideoAdDidLoad:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
    
}
- (void)nativeExpressRewardedVideoAd:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error{
    
}
- (void)nativeExpressRewardedVideoAdDidDownLoadVideo:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
    
}
- (void)nativeExpressRewardedVideoAdViewRenderSuccess:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
    
}
- (void)nativeExpressRewardedVideoAdViewRenderFail:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd error:(NSError *_Nullable)error{
    
}
- (void)nativeExpressRewardedVideoAdWillVisible:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
    
}
- (void)nativeExpressRewardedVideoAdDidVisible:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
    
}
- (void)nativeExpressRewardedVideoAdWillClose:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
    
}
- (void)nativeExpressRewardedVideoAdDidClose:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
    
    [self.rewardedAd loadAdData];
}
- (void)nativeExpressRewardedVideoAdDidClick:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
    
}
- (void)nativeExpressRewardedVideoAdDidClickSkip:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
    
}

- (void)nativeExpressRewardedVideoAdDidPlayFinish:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error{
    
}

- (void)nativeExpressRewardedVideoAdServerRewardDidSucceed:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd verify:(BOOL)verify{
    
}
- (void)nativeExpressRewardedVideoAdServerRewardDidFail:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
    
}

#pragma mark -- rewardedVideo
- (void)rewardedVideoAdDidLoad:(BURewardedVideoAd *)rewardedVideoAd{
    
}

- (void)rewardedVideoAd:(BURewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error{
    
}
- (void)rewardedVideoAdVideoDidLoad:(BURewardedVideoAd *)rewardedVideoAd{
    
}
- (void)rewardedVideoAdWillVisible:(BURewardedVideoAd *)rewardedVideoAd{
    
}

- (void)rewardedVideoAdDidVisible:(BURewardedVideoAd *)rewardedVideoAd{
    
}

- (void)rewardedVideoAdWillClose:(BURewardedVideoAd *)rewardedVideoAd{
    
}
- (void)rewardedVideoAdDidClose:(BURewardedVideoAd *)rewardedVideoAd{
    
}

- (void)rewardedVideoAdDidClick:(BURewardedVideoAd *)rewardedVideoAd{
    
}

- (void)rewardedVideoAdDidPlayFinish:(BURewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error{
    
}

- (void)rewardedVideoAdServerRewardDidSucceed:(BURewardedVideoAd *)rewardedVideoAd verify:(BOOL)verify{
    
}

- (void)rewardedVideoAdServerRewardDidFail:(BURewardedVideoAd *)rewardedVideoAd{
    
}

- (void)rewardedVideoAdDidClickSkip:(BURewardedVideoAd *)rewardedVideoAd{
    
}

- (void)loadDrawaData {
    BUAdSlot *slot1 = [[BUAdSlot alloc] init];
    slot1.ID = @"940033748";
    slot1.AdType = BUAdSlotAdTypeDrawVideo; //required
    slot1.isOriginAd = YES; //required
    slot1.position = BUAdSlotPositionTop;
    slot1.imgSize = [BUSize sizeBy:BUProposalSize_DrawFullScreen];
    slot1.isSupportDeepLink = YES;
    
    if (!self.nativeExpressAdManager) {
        self.nativeExpressAdManager = [[BUNativeExpressAdManager alloc] initWithSlot:slot1 adSize:self.view.bounds.size];
    }
    self.nativeExpressAdManager.adSize = self.view.bounds.size;
    self.nativeExpressAdManager.delegate = self;
    [self.nativeExpressAdManager loadAd:3];
}

#pragma --mark  draw信息流
-(void)loadBannerAd{
    CGFloat screenWidth = CGRectGetWidth([UIScreen mainScreen].bounds);
    CGFloat bannerHeigh = screenWidth/600*150;
    BUSize *imgSize = [BUSize sizeBy:BUProposalSize_Banner600_150];
    BUNativeExpressBannerView *bannerView = [[BUNativeExpressBannerView alloc] initWithSlotID:@"940033814" rootViewController:self imgSize:imgSize adSize:CGSizeMake(screenWidth, bannerHeigh) IsSupportDeepLink:YES];
    bannerView.frame = CGRectMake(0, 100, screenWidth, bannerHeigh);
    bannerView.backgroundColor = [UIColor greenColor];
    bannerView.delegate = self;
    [self.view addSubview:bannerView];
    [bannerView loadAdData];
}

- (void)nativeExpressBannerAdViewDidLoad:(BUNativeExpressBannerView *)bannerAdView{
    
}

- (void)nativeExpressBannerAdView:(BUNativeExpressBannerView *)bannerAdView didLoadFailWithError:(NSError *_Nullable)error{
    
}
- (void)nativeExpressBannerAdViewRenderSuccess:(BUNativeExpressBannerView *)bannerAdView{
    
}

- (void)nativeExpressBannerAdViewRenderFail:(BUNativeExpressBannerView *)bannerAdView error:(NSError * __nullable)error{
    
}

- (void)nativeExpressBannerAdViewWillBecomVisible:(BUNativeExpressBannerView *)bannerAdView{
    
}
- (void)nativeExpressBannerAdViewDidClick:(BUNativeExpressBannerView *)bannerAdView{
    
}
- (void)nativeExpressBannerAdView:(BUNativeExpressBannerView *)bannerAdView dislikeWithReason:(NSArray<BUDislikeWords *> *_Nullable)filterwords{
    
}


- (void)loadNativeAd {
    BUNativeAd *nad = [[BUNativeAd alloc] init];;
    BUAdSlot *slot1 = [[BUAdSlot alloc] init];
    BUSize *imgSize1 = [[BUSize alloc] init];
    imgSize1.width = 1080;
    imgSize1.height = 1920;
    slot1.ID = @"940033121";
    slot1.AdType = BUAdSlotAdTypeFeed;
    slot1.position = BUAdSlotPositionFeed;
    slot1.imgSize = imgSize1;
    slot1.isSupportDeepLink = YES;
    nad.adslot = slot1;
    
    nad.rootViewController = self;
    nad.delegate = self;
    [nad loadAdData];
}

- (void)nativeAdDidLoad:(BUNativeAd *)nativeAd{
    
}
- (void)nativeAd:(BUNativeAd *)nativeAd didFailWithError:(NSError *_Nullable)error{
    
}
- (void)nativeAdDidBecomeVisible:(BUNativeAd *)nativeAd{
    
}
- (void)nativeAdDidCloseOtherController:(BUNativeAd *)nativeAd interactionType:(BUInteractionType)interactionType{
    
}
- (void)nativeAdDidClick:(BUNativeAd *)nativeAd withView:(UIView *_Nullable)view{
    
}
- (void)nativeAd:(BUNativeAd *_Nullable)nativeAd dislikeWithReason:(NSArray<BUDislikeWords *> *_Nullable)filterWords{
    
}

#pragma mark --信息流
- (void)loadFeadAd{
    
    BUAdSlot *slot1 = [[BUAdSlot alloc] init];
    slot1.ID = @"940033121";
    slot1.AdType = BUAdSlotAdTypeFeed;
    BUSize *imgSize = [BUSize sizeBy:BUProposalSize_Feed228_150];
    slot1.imgSize = imgSize;
    slot1.position = BUAdSlotPositionFeed;
    slot1.isSupportDeepLink = YES;
    
    // self.nativeExpressAdManager可以重用
    if (!self.nativeExpressAdManager) {
        self.nativeExpressAdManager = [[BUNativeExpressAdManager alloc] initWithSlot:slot1 adSize:CGSizeMake(300, 300)];
    }
    self.nativeExpressAdManager.adSize = CGSizeMake(300, 300);
    self.nativeExpressAdManager.delegate = self;
    [self.nativeExpressAdManager loadAd:4];
}

- (void)nativeExpressAdSuccessToLoad:(BUNativeExpressAdManager *)nativeExpressAd views:(NSArray<__kindof BUNativeExpressAdView *> *)views{
    
    [self.expressAdViews removeAllObjects];//【重要】不能保存太多view，需要在合适的时机手动释放不用的，否则内存会过大
    if (views.count) {
        [self.expressAdViews addObjectsFromArray:views];
        [views enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            BUNativeExpressAdView *expressView = (BUNativeExpressAdView *)obj;
            expressView.rootViewController = self;
            [expressView render];
        }];
    }
    [self.tableview reloadData];
}


- (void)nativeExpressAdFailToLoad:(BUNativeExpressAdManager *)nativeExpressAd error:(NSError *_Nullable)error{
    
}


- (void)nativeExpressAdViewRenderSuccess:(BUNativeExpressAdView *)nativeExpressAdView{
    
}

- (void)nativeExpressAdViewRenderFail:(BUNativeExpressAdView *)nativeExpressAdView error:(NSError *_Nullable)error{
    
}

- (void)nativeExpressAdViewWillShow:(BUNativeExpressAdView *)nativeExpressAdView{
    
}

- (void)nativeExpressAdViewDidClick:(BUNativeExpressAdView *)nativeExpressAdView{
    NSLog(@"%@",nativeExpressAdView);
}

- (void)nativeExpressAdViewPlayerDidPlayFinish:(BUNativeExpressAdView *)nativeExpressAdView error:(NSError *)error{
    
}

- (void)nativeExpressAdView:(BUNativeExpressAdView *)nativeExpressAdView dislikeWithReason:(NSArray<BUDislikeWords *> *)filterWords{
    
}
- (void)nativeExpressAdViewWillPresentScreen:(BUNativeExpressAdView *)nativeExpressAdView{
    
}

#pragma mark --模板渲染
- (void)nativeAdsManagerSuccessToLoad:(BUNativeAdsManager *)adsManager nativeAds:(NSArray<BUNativeAd *> *_Nullable)nativeAdDataArray{
    
    [self.expressAdViews removeAllObjects];//【重要】不能保存太多view，需要在合适的时机手动释放不用的，否则内存会过大
    if (nativeAdDataArray.count) {
        [self.expressAdViews addObjectsFromArray:nativeAdDataArray];
        [nativeAdDataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            BUNativeExpressAdView *expressView = (BUNativeExpressAdView *)obj;
            expressView.rootViewController = self;
            [expressView render];
        }];
    }
    [self.tableview reloadData];
    
}

- (void)nativeAdsManager:(BUNativeAdsManager *)adsManager didFailWithError:(NSError *_Nullable)error{
    
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row % 2 == 0) {
        UIView *view = [self.expressAdViews objectAtIndex:indexPath.row / 2];
        return view.bounds.size.height;
    }
    else {
        return 44;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.expressAdViews.count * 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    if (indexPath.row % 2 == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"BUDNativeExpressCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        // 重用BUNativeExpressAdView，先把之前的广告试图取下来，再添加上当前视图
        UIView *subView = (UIView *)[cell.contentView viewWithTag:1000];
        if ([subView superview]) {
            [subView removeFromSuperview];
        }
        
        UIView *view = [self.expressAdViews objectAtIndex:indexPath.row / 2];
        view.tag = 1000;
        [cell.contentView addSubview:view];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"BUDSplitNativeExpressCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
    }
    return cell;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
